package com.wpam.scrabble.mobile.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.wpam.scrabble.mobile.R;
import com.wpam.scrabble.mobile.communication.CommunicationManager;
import com.wpam.scrabble.mobile.communication.bt.BluetoothManager;

public class ServerSearchActivity extends Activity implements OnClickListener {
	
	private ServerAdapter adapter_;
	private BluetoothManager btManager_;
	private String serverType_;	//TODO: Convert to constants?
	
	private TextView statusText_;
	private ProgressBar progressBar_;
	private Button refreshButton_;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        Bundle b = getIntent().getExtras();
        if (b != null)
        	serverType_ = b.getString("serverType");
        setContentView(R.layout.activity_server_search);
        
    	statusText_ = (TextView) findViewById(R.id.statusText);
    	progressBar_ = (ProgressBar) findViewById(R.id.serverSearchProgressBar);
    	refreshButton_ = (Button) findViewById(R.id.refreshButton);
        refreshButton_.setOnClickListener(this);
        
        ListView usersList = (ListView) findViewById(R.id.serversList);
        
        if (adapter_ == null) {
        	adapter_ = new ServerAdapter();
        	usersList.setAdapter(adapter_);
        }
        
        if (serverType_.equals("BT")) {
        	btManager_ = BluetoothManager.getInstance(this);
	        if (!btManager_.isBtAvailable()) {
	        	Toast.makeText(this, getResources().getString(R.string.device_does_not_support_bt), Toast.LENGTH_SHORT).show();
	        	finish();
	        }
	        if (!btManager_.isBtEnabled())
	        	btManager_.turnRadioOn();
	        else
	        	onActivityResult(BluetoothManager.REQUEST_ENABLE_BT, Activity.RESULT_OK, null);
	        
	        CommunicationManager.getInstance().startDiscoveryListener(this, adapter_, statusText_);
        }
        else {
        	Toast.makeText(this, getResources().getString(R.string.web_server_not_implemented), Toast.LENGTH_SHORT).show();
        	finish();
        }
    }
    
    @Override
	protected void onDestroy() {

    	try {
    		CommunicationManager.getInstance().stopDiscoveryListener();
    	}
    	catch (IllegalArgumentException e) {
    		//e.printStackTrace();
    	}
		CommunicationManager.getInstance(this).stopNetworkActions();
		CommunicationManager.disconnectClient();
		super.onDestroy();
	}

	@Override
	protected void onPause() {

    	try {
    		CommunicationManager.getInstance().stopDiscoveryListener();
    	}
    	catch (IllegalArgumentException e) {
    		//e.printStackTrace();
    	}
		super.onPause();
	}

	@Override
	protected void onResume() {

		CommunicationManager.getInstance(this);
		CommunicationManager.getInstance().resumeDiscoveryListener();
		super.onResume();
	}

	public class ServerAdapter extends ArrayAdapter<ServerInfo> {

		private int[] colors = new int[] { getResources().getInteger(R.color.FirstRow), getResources().getInteger(R.color.SecondRow) };
    	
    	public ServerAdapter() {
    		
    		super(ServerSearchActivity.this, R.layout.user_row);
    	}
    	
    	@Override
		public void add(ServerInfo object) {
    		
			if (getPosition(object) == -1)
				super.add(object);
		}
    	
    	@Override
    	public View getView(final int position, View convertView, ViewGroup parent) {
    		
    		View row = null;
    		LayoutInflater inflater = getLayoutInflater();
    		
    		row = inflater.inflate(R.layout.server_row, parent, false);
    		
    		TextView name = (TextView) row.findViewById(R.id.serverName);
    		name.setText(getItem(position).getName()); 
    		if (getItem(position).isServerConfirmed()) {
	    		ImageView image = (ImageView) row.findViewById(R.id.isServerImage);
	    		image.setImageResource(R.drawable.ic_launcher);
    		}
    		Button connectButton = (Button) row.findViewById(R.id.connectToServerButton);
    		
    		connectButton.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					btManager_.runConnect(getItem(position).getDevice());
				}
			});
    		
    		connectButton.setTag(getItem(position));
    		
    		int colorPos = position % colors.length;
    		row.setBackgroundColor(colors[colorPos]);
    		return row;
    	}
    }
    
	public ServerAdapter getAdapter() {
		return adapter_;
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		btManager_.onActivityResult(requestCode, resultCode, data);
	}
	
	public void uiSetStatus(String txt, boolean loading, boolean refreshEnabled) {
		
		if (loading)
			progressBar_.setVisibility(View.VISIBLE);
		else
			progressBar_.setVisibility(View.GONE);
		
		refreshButton_.setEnabled(refreshEnabled);
		statusText_.setText(txt);
	}

	public void onClick(View v) {
		
		if (v.getId() == R.id.refreshButton) {
			getAdapter().clear();
			CommunicationManager.getInstance().stopNetworkActions();
			CommunicationManager.disconnectClient();
			btManager_.runServerSearch();
		}
	}
}
